package com.stylefeng.guns.modular.system.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.util.AlipayConfig;
import com.stylefeng.guns.core.util.DateUtils;
import com.stylefeng.guns.modular.system.model.Record;
import com.stylefeng.guns.modular.system.model.Setup;
import com.stylefeng.guns.modular.system.service.IPayResultService;
import com.stylefeng.guns.modular.system.service.IRecordService;
import com.stylefeng.guns.modular.system.service.ISetupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/api/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private IRecordService iRecordService;

    @Autowired
    private IPayResultService payResultService;

    @Autowired
    private ISetupService iSetupService;

    /**
     * 条件判断
     */
    public Setup condition(List<Setup> aliSetupList) {
        Setup aliSetup = null;
        int num = 0; // 用来计数
        try {
            if (aliSetupList != null && aliSetupList.size() > 0) {
                aliSetup = choose(aliSetupList);// 先选中一条数据
                int success_num = payResultService
                        .getSuccessNumByAccount(aliSetup.getAccount());
                String totalPrice = payResultService
                        .getTotalPrice(aliSetup.getAccount());
                double total_price = Double.parseDouble(totalPrice == null ? "0" : totalPrice);
                // 判断总成功条数，设置数>总条数，说明可以继续使用该帐号
                if (aliSetup.getSuccessNum() < success_num) {
                    num++;
                }
                if (Double.parseDouble(aliSetup.getMoney()) < total_price) {
                    num++;
                }
                if (num > 0) {
                    if (num > 1) {
                        iSetupService.updisUse(aliSetup.getAccount());// 这个是两个都满足的话，这条可以一直不用了
                    }
                    aliSetupList.remove(aliSetup);// 移除
                    aliSetup = condition(aliSetupList);// 重新选择一条
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
        }
        return aliSetup;
    }

    // 选择相应的数据
    public Setup choose(List<Setup> aliSetupList) {
        List<Setup> aliSetUp = null;
        int index = 0;
        try {
            aliSetUp = aliSetupList;
            index = rand(aliSetUp.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aliSetUp.get(index);

    }

    // 随机数
    public int rand(int length) {
        return (int) (Math.random() * length);
    }


    @RequestMapping("/requestAlipay/{channel}/{goods}/{price}")
    public void requestAlipay(HttpServletResponse response, @PathVariable("channel") String channel,
                              @PathVariable("goods") String goods, @PathVariable("price") String price) {

        Record record = null;

        record = new Record();

        record.setChannel(channel);
        record.setGoods(goods);
        record.setPrice(price);
        record.setStatus(1);
        record.setDate(new Date());
        //添加数据
        iRecordService.insertAllColumn(record);

        Setup aliSetup = null;

        List<Setup> aliSetupList = iSetupService.selectList(null);

        aliSetup = condition(aliSetupList);

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = DateUtils.getOrderIdByTime();
        // 订单名称，必填
        String subject = null;
        if (!StringUtils.isEmpty(channel)) {
            try {
                subject = new String(channel.getBytes("ISO-8859-1"), "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 付款金额，必填
        String total_amount = price;
        // 商品描述，可空
        String body = goods;
        // 超时时间 可空
        String timeout_express = "2m";
        // 销售产品码 必填
        String product_code = "QUICK_WAP_WAY";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        // 调用RSA签名方式

        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL,
                aliSetup.getAppid(), aliSetup.getRsaPrimaryKey(),
                AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                aliSetup.getAliAppKey(), AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);// 直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            record = null;
        }

    }
}
